package com.djf.djfcs.service.impl;

import com.djf.djfcs.entity.Order;
import com.djf.djfcs.entity.User;
import com.djf.djfcs.entity.UserDelivery;
import com.djf.djfcs.mapper.OrderMapper;
import com.djf.djfcs.mapper.UserDeliveryMapper;
import com.djf.djfcs.mapper.UserMapper;
import com.djf.djfcs.service.DataGeneratorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;

/**
 * 数据生成器服务实现类
 * 
 * @author djf
 * @since 2025-01-01
 */
@Slf4j
@Service
public class DataGeneratorServiceImpl implements DataGeneratorService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private UserDeliveryMapper userDeliveryMapper;

    // 随机数据生成常量
    private static final String[] PRODUCT_NAMES = {
        "智能手机", "笔记本电脑", "平板电脑", "智能手表", "蓝牙耳机",
        "数码相机", "游戏手柄", "充电宝", "无线鼠标", "机械键盘",
        "显示器", "音响设备", "路由器", "硬盘", "内存条"
    };

    private static final String[] ORDER_STATUSES = {
        "待支付", "已支付", "已发货", "已完成", "已取消"
    };

    private static final String[] DELIVERY_STATUSES = {
        "待配送", "配送中", "已送达", "配送失败", "已取消"
    };

    private static final String[] CITIES = {
        "北京市", "上海市", "广州市", "深圳市", "杭州市",
        "南京市", "武汉市", "成都市", "西安市", "重庆市"
    };

    private static final String[] SURNAMES = {
        "王", "李", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴",
        "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗"
    };

    private static final String[] GIVEN_NAMES = {
        "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军",
        "洋", "勇", "艳", "杰", "涛", "明", "超", "秀兰", "霞", "平"
    };

    // 月份格式验证正则
    private static final Pattern MONTH_PATTERN = Pattern.compile("^\\d{4}-\\d{2}$");

    @Override
    @Transactional
    public String generateCompleteData(Integer userCount, Integer orderCount, String startMonth, String endMonth) {
        try {
            log.info("开始批量生成数据 - 用户数量: {}, 订单数量: {}, 开始月份: {}, 结束月份: {}", 
                    userCount, orderCount, startMonth, endMonth);

            // 参数验证和默认值设置
            userCount = (userCount == null || userCount <= 0) ? 100 : userCount;
            orderCount = (orderCount == null || orderCount <= 0) ? 1000 : orderCount;
            startMonth = (startMonth == null || startMonth.trim().isEmpty()) ? "2025-01" : startMonth.trim();
            endMonth = (endMonth == null || endMonth.trim().isEmpty()) ? "2025-12" : endMonth.trim();

            // 验证月份格式
            if (!isValidMonthFormat(startMonth) || !isValidMonthFormat(endMonth)) {
                return "月份格式错误，请使用 YYYY-MM 格式，如：2025-01";
            }

            // 1. 生成用户数据
            List<User> users = generateUserList(userCount);
            for (User user : users) {
                userMapper.insert(user);
            }
            log.info("成功生成用户数据: {} 条", users.size());

            // 2. 从数据库中重新查询用户数据，确保获取到正确的ID
            List<User> dbUsers = userMapper.selectList(null);
            if (dbUsers.isEmpty()) {
                return "用户数据生成失败，无法继续生成订单和配送数据";
            }
            log.info("从数据库查询到用户数据: {} 条", dbUsers.size());

            // 3. 生成订单数据（使用数据库中的用户数据）
            List<Order> orders = generateOrderList(orderCount, dbUsers, startMonth, endMonth);
            for (Order order : orders) {
                orderMapper.insert(order);
            }
            log.info("成功生成订单数据: {} 条", orders.size());

            // 4. 生成配送数据（每个订单对应一个配送，使用数据库中的用户数据）
            List<UserDelivery> deliveries = generateDeliveryList(orders, dbUsers, startMonth, endMonth);
            for (UserDelivery delivery : deliveries) {
                userDeliveryMapper.insert(delivery);
            }
            log.info("成功生成配送数据: {} 条", deliveries.size());

            String result = String.format("批量数据生成完成！用户: %d 条，订单: %d 条，配送: %d 条", 
                    users.size(), orders.size(), deliveries.size());
            log.info(result);
            return result;

        } catch (Exception e) {
            log.error("批量生成数据失败", e);
            return "批量生成数据失败：" + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String generateUsers(Integer count) {
        try {
            count = (count == null || count <= 0) ? 100 : count;
            log.info("开始生成用户数据，数量: {}", count);

            List<User> users = generateUserList(count);
            for (User user : users) {
                userMapper.insert(user);
            }

            String result = "成功生成用户数据: " + users.size() + " 条";
            log.info(result);
            return result;

        } catch (Exception e) {
            log.error("生成用户数据失败", e);
            return "生成用户数据失败：" + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String generateOrders(Integer count, String startMonth, String endMonth) {
        try {
            count = (count == null || count <= 0) ? 1000 : count;
            startMonth = (startMonth == null || startMonth.trim().isEmpty()) ? "2025-01" : startMonth.trim();
            endMonth = (endMonth == null || endMonth.trim().isEmpty()) ? "2025-12" : endMonth.trim();

            // 验证月份格式
            if (!isValidMonthFormat(startMonth) || !isValidMonthFormat(endMonth)) {
                return "月份格式错误，请使用 YYYY-MM 格式，如：2025-01";
            }

            log.info("开始生成订单数据，数量: {}, 开始月份: {}, 结束月份: {}", count, startMonth, endMonth);

            // 获取现有用户
            List<User> users = userMapper.selectList(null);
            if (users.isEmpty()) {
                return "请先生成用户数据";
            }

            List<Order> orders = generateOrderList(count, users, startMonth, endMonth);
            for (Order order : orders) {
                orderMapper.insert(order);
            }

            String result = "成功生成订单数据: " + orders.size() + " 条";
            log.info(result);
            return result;

        } catch (Exception e) {
            log.error("生成订单数据失败", e);
            return "生成订单数据失败：" + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String generateDeliveries(String startMonth, String endMonth) {
        try {
            startMonth = (startMonth == null || startMonth.trim().isEmpty()) ? "2025-01" : startMonth.trim();
            endMonth = (endMonth == null || endMonth.trim().isEmpty()) ? "2025-12" : endMonth.trim();

            // 验证月份格式
            if (!isValidMonthFormat(startMonth) || !isValidMonthFormat(endMonth)) {
                return "月份格式错误，请使用 YYYY-MM 格式，如：2025-01";
            }

            log.info("开始生成配送数据，开始月份: {}, 结束月份: {}", startMonth, endMonth);

            // 获取现有订单和用户
            List<Order> orders = orderMapper.selectList(null);
            List<User> users = userMapper.selectList(null);
            
            if (orders.isEmpty()) {
                return "请先生成订单数据";
            }
            if (users.isEmpty()) {
                return "请先生成用户数据";
            }

            List<UserDelivery> deliveries = generateDeliveryList(orders, users, startMonth, endMonth);
            for (UserDelivery delivery : deliveries) {
                userDeliveryMapper.insert(delivery);
            }

            String result = "成功生成配送数据: " + deliveries.size() + " 条";
            log.info(result);
            return result;

        } catch (Exception e) {
            log.error("生成配送数据失败", e);
            return "生成配送数据失败：" + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String clearAllData() {
        try {
            log.info("开始清空所有数据");

            // 清空配送数据
            userDeliveryMapper.delete(null);
            log.info("清空配送数据完成");

            // 清空订单数据
            orderMapper.delete(null);
            log.info("清空订单数据完成");

            // 清空用户数据
            userMapper.delete(null);
            log.info("清空用户数据完成");

            String result = "所有数据清空完成";
            log.info(result);
            return result;

        } catch (Exception e) {
            log.error("清空数据失败", e);
            return "清空数据失败：" + e.getMessage();
        }
    }

    @Override
    public String getServiceStatus() {
        try {
            long userCount = userMapper.selectCount(null);
            long orderCount = orderMapper.selectCount(null);
            long deliveryCount = userDeliveryMapper.selectCount(null);

            return String.format("服务状态正常 - 用户数据: %d 条，订单数据: %d 条，配送数据: %d 条", 
                    userCount, orderCount, deliveryCount);

        } catch (Exception e) {
            log.error("获取服务状态失败", e);
            return "获取服务状态失败：" + e.getMessage();
        }
    }

    /**
     * 生成用户列表
     */
    private List<User> generateUserList(int count) {
        List<User> users = new ArrayList<>();
        Random random = new Random();
        
        for (int i = 1; i <= count; i++) {
            User user = new User();
            user.setUserName("user" + String.format("%06d", i));
            user.setPhone(generateRandomPhone());
            user.setEmail(user.getUserName() + "@example.com");
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            users.add(user);
        }
        
        return users;
    }

    /**
     * 生成订单列表
     */
    private List<Order> generateOrderList(int count, List<User> users, String startMonth, String endMonth) {
        List<Order> orders = new ArrayList<>();
        Random random = new Random();
        
        if (users.isEmpty()) {
            log.warn("用户列表为空，无法生成订单数据");
            return orders;
        }
        
        for (int i = 1; i <= count; i++) {
            User randomUser = users.get(random.nextInt(users.size()));
            
            // 确保用户ID不为空
            if (randomUser.getId() == null) {
                log.warn("用户ID为空，跳过订单生成: {}", randomUser.getUserName());
                continue;
            }
            
            Order order = new Order();
            
            // 生成订单号：ORD + 年月 + 序号
            LocalDateTime orderTime = generateRandomDateTime(startMonth, endMonth);
            String yearMonth = orderTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
            order.setOrderNo("ORD" + yearMonth + String.format("%04d", i));
            
            order.setTenantId("tenant_" + (random.nextInt(10) + 1));
            order.setUserId(randomUser.getId());
            order.setProductName(PRODUCT_NAMES[random.nextInt(PRODUCT_NAMES.length)]);
            order.setTotalAmount(BigDecimal.valueOf(10 + random.nextDouble() * 990).setScale(2, BigDecimal.ROUND_HALF_UP));
            order.setStatus(ORDER_STATUSES[random.nextInt(ORDER_STATUSES.length)]);
            order.setCreateTime(orderTime);
            order.setUpdateTime(LocalDateTime.now());
            order.setRemark("系统生成的测试订单数据 - 订单号：" + order.getOrderNo() + "，关联用户：" + randomUser.getUserName());
            order.setDeleted(0);
            
            orders.add(order);
        }
        
        log.info("实际生成订单数量: {}", orders.size());
        return orders;
    }

    /**
     * 生成配送列表（每个订单对应一个配送）
     */
    private List<UserDelivery> generateDeliveryList(List<Order> orders, List<User> users, String startMonth, String endMonth) {
        List<UserDelivery> deliveries = new ArrayList<>();
        Random random = new Random();
        Map<Long, User> userMap = new HashMap<>();
        
        // 构建用户映射，过滤掉ID为空的用户
        for (User user : users) {
            if (user.getId() != null) {
                userMap.put(user.getId(), user);
            }
        }
        
        if (userMap.isEmpty()) {
            log.warn("没有有效的用户数据，无法生成配送数据");
            return deliveries;
        }
        
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            
            // 验证订单的用户ID
            if (order.getUserId() == null) {
                log.warn("订单用户ID为空，跳过配送生成: {}", order.getOrderNo());
                continue;
            }
            
            User user = userMap.get(order.getUserId());
            
            if (user != null) {
                UserDelivery delivery = new UserDelivery();
                
                // 生成配送单号：基于订单号后8位 + 序号
                String orderNoSuffix = order.getOrderNo().substring(Math.max(0, order.getOrderNo().length() - 8));
                delivery.setDeliveryNo("DEL" + orderNoSuffix + String.format("%03d", i + 1));
                
                delivery.setOrderId(order.getId());
                delivery.setUserId(order.getUserId());
                delivery.setReceiverName(generateRandomName());
                delivery.setReceiverPhone(user.getPhone());
                delivery.setReceiverAddress(generateRandomAddress());
                delivery.setDeliveryStatus(DELIVERY_STATUSES[random.nextInt(DELIVERY_STATUSES.length)]);
                
                // 配送时间应该晚于订单时间
                LocalDateTime deliveryTime = order.getCreateTime().plusHours(random.nextInt(72) + 1);
                delivery.setDeliveryTime(deliveryTime);
                
                delivery.setCreateTime(order.getCreateTime());
                delivery.setUpdateTime(LocalDateTime.now());
                delivery.setRemark("系统生成的测试配送数据 - 配送单号：" + delivery.getDeliveryNo() + "，关联订单：" + order.getOrderNo() + "，关联用户：" + user.getUserName());
                delivery.setDeleted(0);
                
                deliveries.add(delivery);
            } else {
                log.warn("找不到订单对应的用户，跳过配送生成 - 订单号: {}，用户ID: {}", order.getOrderNo(), order.getUserId());
            }
        }
        
        log.info("实际生成配送数量: {}", deliveries.size());
        return deliveries;
    }

    /**
     * 生成随机手机号
     */
    private String generateRandomPhone() {
        return "1" + String.format("%010d", ThreadLocalRandom.current().nextLong(1000000000L, 9999999999L));
    }

    /**
     * 生成随机姓名
     */
    private String generateRandomName() {
        Random random = new Random();
        String surname = SURNAMES[random.nextInt(SURNAMES.length)];
        String givenName = GIVEN_NAMES[random.nextInt(GIVEN_NAMES.length)];
        return surname + givenName;
    }

    /**
     * 生成随机地址
     */
    private String generateRandomAddress() {
        Random random = new Random();
        String city = CITIES[random.nextInt(CITIES.length)];
        String district = "区" + (random.nextInt(20) + 1);
        String street = "街道" + (random.nextInt(100) + 1) + "号";
        return city + district + street;
    }

    /**
     * 生成指定月份范围内的随机时间
     */
    private LocalDateTime generateRandomDateTime(String startMonth, String endMonth) {
        try {
            // 解析开始和结束月份
            String[] startParts = startMonth.split("-");
            String[] endParts = endMonth.split("-");
            
            int startYear = Integer.parseInt(startParts[0]);
            int startMonthNum = Integer.parseInt(startParts[1]);
            int endYear = Integer.parseInt(endParts[0]);
            int endMonthNum = Integer.parseInt(endParts[1]);
            
            // 生成随机年月
            Random random = new Random();
            int randomYear, randomMonth;
            
            if (startYear == endYear) {
                randomYear = startYear;
                randomMonth = startMonthNum + random.nextInt(endMonthNum - startMonthNum + 1);
            } else {
                // 跨年情况，简化处理
                randomYear = startYear + random.nextInt(endYear - startYear + 1);
                if (randomYear == startYear) {
                    randomMonth = startMonthNum + random.nextInt(12 - startMonthNum + 1);
                } else if (randomYear == endYear) {
                    randomMonth = 1 + random.nextInt(endMonthNum);
                } else {
                    randomMonth = 1 + random.nextInt(12);
                }
            }
            
            // 生成随机日期
            int daysInMonth = getDaysInMonth(randomYear, randomMonth);
            int randomDay = 1 + random.nextInt(daysInMonth);
            
            // 生成随机时间
            int randomHour = random.nextInt(24);
            int randomMinute = random.nextInt(60);
            int randomSecond = random.nextInt(60);
            
            return LocalDateTime.of(randomYear, randomMonth, randomDay, randomHour, randomMinute, randomSecond);
            
        } catch (Exception e) {
            log.warn("生成随机时间失败，使用当前时间: {}", e.getMessage());
            return LocalDateTime.now();
        }
    }

    /**
     * 获取指定年月的天数
     */
    private int getDaysInMonth(int year, int month) {
        switch (month) {
            case 2:
                return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            default:
                return 31;
        }
    }

    /**
     * 验证月份格式
     */
    private boolean isValidMonthFormat(String month) {
        if (month == null || !MONTH_PATTERN.matcher(month).matches()) {
            return false;
        }
        
        try {
            String[] parts = month.split("-");
            int year = Integer.parseInt(parts[0]);
            int monthNum = Integer.parseInt(parts[1]);
            
            return year >= 2020 && year <= 2030 && monthNum >= 1 && monthNum <= 12;
        } catch (Exception e) {
            return false;
        }
    }
}